package com.example.caorl.jdbcaop.util;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class HikariUtil {

	private static String driverClassName;
	private static String url;
	private static String username;
	private static String password;

	private static DataSource ds;

	private HikariUtil(){}


	static{
		try {
			//ClassLoader loader=Thread.currentThread().getClass().getClassLoader();
			InputStream in=HikariUtil.class.getClassLoader().getResourceAsStream("db.properties");
			Properties p=new Properties();
			p.load(in);//加载必须在调用之前
			driverClassName = p.getProperty("driver");
			url = p.getProperty("url");
			username = p.getProperty("username");
			password = p.getProperty("password");

			
			//druid连接池获取对象
			HikariDataSource hikariDataSource = new HikariDataSource();
			hikariDataSource.setMaximumPoolSize(100);
			hikariDataSource.setDriverClassName(driverClassName);
//			hikariDataSource.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
//			hikariDataSource.setDataSourceClassName(driverClassName);
			hikariDataSource.setJdbcUrl(url);
			hikariDataSource.setUsername(username);
			hikariDataSource.setPassword(password);
			hikariDataSource.addDataSourceProperty("url", url);
			hikariDataSource.addDataSourceProperty("user", username);
			hikariDataSource.addDataSourceProperty("password", password);
			hikariDataSource.addDataSourceProperty("cachePrepStmts", true);
			hikariDataSource.addDataSourceProperty("prepStmtCacheSize", 250);
			hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
			hikariDataSource.addDataSourceProperty("useServerPrepStmts", true);
			ds=hikariDataSource;

			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//解决硬编码
	}	
	
	//工具类的异常一般都是抛出的，因为别人用你的代码产生的异常你无法解决
	/**
	 * 用于获取连接数据库的对象
	 * @return Connection对象
	 * @throws Exception
	 */
	public static Connection getConn() throws Exception{
		//在工具类中，方法里面的对象一般都不会重复调用，所以直接返回就可以了
		//return DriverManager.getConnection(url,username,password);
		return ds.getConnection();//通过连接池获取对数据库的连接
	}
	
	//在这个方法中，产生的异常可以try/catch
	/**
	 * close()方法用于关闭数据库连接过程中出现的一些资源
	 * 
	 */
	public static void close(Connection conn,Statement st,ResultSet rs){
		try {
			if(conn!=null){
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if(st!=null){
				st.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if(rs!=null){
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}
